//
//  SWAPIComponent.swift
//  BaseDemo
//
//  Created by linhan on 16/2/25.
//  Copyright © 2016年 me. All rights reserved.
//

import Foundation

private var ReqPoolKey: Void?

protocol SWAPIComponent:SWRequestDelegate
{
    
}

extension SWAPIComponent
{
    
    func load(_ request:SWBaseRequest)
    {
        appendToPool(request)
        request.delegate = self
        request.load()
    }
    
    func upload(request:SWBaseRequest)
    {
        
    }
    
    //取消当前页面所有请求
    func cancelAllRequest()
    {
        if let requests = _requestPool
        {
            for req in requests
            {
                req.cancel()
            }
        }
    }
    
    func request(_ request:SWBaseRequest, didFinishLoading data:Data, fromCache cache:Bool)
    {
        
    }
    
    func request(_ request:SWBaseRequest, didFinishLoading string:String, fromCache cache:Bool)
    {
        
    }
    
    func request(_ request:SWBaseRequest, APISuccess data:Any, fromCache cache:Bool)
    {
        //print("SWAPIComponent APISuccess", request.binds ,data)
    }
    
    func request(_ request:SWBaseRequest, APIFailed error:NSError)
    {
        
    }
    
    private func appendToPool(_ request:SWBaseRequest)
    {
        var pool:[SWBaseRequest] = _requestPool ?? []
        pool.append(request)
        objc_setAssociatedObject(self, &ReqPoolKey, pool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    
    private var _requestPool: [SWBaseRequest]? {
        return objc_getAssociatedObject(self, &ReqPoolKey) as? [SWBaseRequest]
    }
    
//    private func setRequestPool(task: [SWBaseRequest]?) {
//        objc_setAssociatedObject(self, &ReqPoolKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//    }
    
    

    
    
}
